import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login'
import Main from "@/views/Main";
import axios from "axios";
import store from "@/store/index"
import NotFound from "@/views/NotFound.vue";
import DictData from "@/views/sys/DictData.vue";

Vue.use(VueRouter)

const routes = [
    {
        path: "/",
        name: "Login",
        component: Login,
    },
    {
        path: "/login",
        name: "Logins",
        component: Login,
    },
    {
        path: "/main",
        name: "Main",
        component: Main,
    }
]

const router = new VueRouter({
    routes
})

//全局路由守卫
router.beforeEach((to, from, next) => {
    if (to.path == "/login" || to.path == "/") {
        //放行
        next();
    } else {
        //判断是否登录
        let token = store.state.token;
        if (token) {
            if (store.state.userInfo.username == '未登录' || router.getRoutes().length < 4) {
                axios.get("/api/getInfo")
                    .then((res) => {
                        if (res.data.code == 200) {
                            store.commit("setUserInfo", {
                                "username": res.data.username,
                                "avatar": res.data.avatar,
                                "permissions": res.data.permissions
                            });
                            //保存动态菜单
                            store.commit("setMenus", res.data.menus);
                            //保存动态路由
                            formatRouter(res.data.menus).forEach((menu) => {
                                router.addRoute('Main', menu);
                            })
                            //添加字典数据
                            router.addRoute('Main', {path: "/dict/data", component: DictData})
                            router.addRoute('Main', {
                                path: "/clue/clueData",
                                component: () => import('@/views/tb/ClueData.vue')
                            })
                            //最后添加404路由
                            router.addRoute({path: "*", component: NotFound})
                            next({...to, replace: true})
                            // next()
                        } else {
                            this.$message.error(res.data.msg);
                        }
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            }
            next();
        } else {
            Vue.prototype.$message.error("无权访问，请先登录");
            next("/login");
        }


        //构造路由数据
        let formatRouter = (menus) => {
            let myRouters = [];
            menus.forEach((menu) => {
                let myRouter = {
                    path: menu.path || "/not",  //路径不能为空
                    name: menu.menuName
                }
                if (menu.component) {  //必须给每个路由一个组件
                    myRouter.component = () => import('@/views/' + menu.component + '.vue');
                } else {
                    myRouter.component = () => import('@/views/EmptyLayout.vue'); // 空白布局
                }
                if (menu.children) {
                    myRouter.children = formatRouter(menu.children);
                }
                myRouters.push(myRouter);
            })
            return myRouters;
        }
    }
})


// 3. 重置路由的核心方法：用新的matcher替换旧的matcher
export function resetRouter() {
    // 创建一个全新的路由实例（仅含常量路由）
    const newRouter = new VueRouter({
        routes
    })
    // 关键操作：替换matcher，彻底清除动态路由
    router.matcher = newRouter.matcher
}

export default router
